﻿using OpenWaves.ActivityFeed.Web.Modules;
using HttpStatusCode = System.Net.HttpStatusCode;

namespace OpenWaves.ActivityFeed.Web.Handler
{
    public class ActivityFeedApiHandler : HttpHandler
    {
        public ActivityFeedApiHandler() : this(
            ServiceLocator.Resolve<IUserIdentityProvider>(),
            new SubscriptionsModule(
                ServiceLocator.Resolve<IActivityFeedService>(),
                ServiceLocator.Resolve<IUserIdentityProvider>()),
            new UpdatesModule(
                ServiceLocator.Resolve<IUserIdentityProvider>(),
                ServiceLocator.Resolve<IActivityFeedService>(), 
                ServiceLocator.Resolve<IUserGroupMembershipProvider>(),
                ServiceLocator.Resolve<IUpdateDtoBuilder>()),
            new CommentsModule(
                ServiceLocator.Resolve<IActivityFeedService>(),
                ServiceLocator.Resolve<IUserIdentityProvider>(), 
                ServiceLocator.Resolve<IUserProfileProvider>()),
            new LikesModule(
                ServiceLocator.Resolve<IActivityFeedService>(),
                ServiceLocator.Resolve<IUserIdentityProvider>(), 
                ServiceLocator.Resolve<IUserProfileProvider>()),
            new ExtendedApiModule(ServiceLocator.Resolve<IActivityFeedService>(),
                ServiceLocator.Resolve<IUserIdentityProvider>(),
                ServiceLocator.Resolve<IUserProfileProvider>())
            )
        {
        }

        public ActivityFeedApiHandler(IUserIdentityProvider identityProvider, params IRestModule[] modules) : base(modules)
        {
            this.Before += (sender, args) =>
                               {
                                   if (identityProvider.Identity.IsAuthenticated == false)
                                       args.TerminateRequest(HttpStatusCode.Unauthorized);

                                    args.Response.AppendHeader("Cache-Control", "no-cache, must-revalidate");
                                    args.Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
                                    args.Response.AppendHeader("Pragma", "no-cache");
                               };
        }
    }
}